package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @create 2020-05-19 14:16
 */
@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    //查询一二三级属性生成静态化页面
    /*@GetMapping("/")
    public String getBaseCategoryMap(Model model){
        List<Map> baseCategoryMap = productFeignClient.getBaseCategoryMap();
       // model.addAttributes("list",baseCategoryMap);
        model.addAttribute("list",baseCategoryMap);
        return "index/index";
    }*/


    //******************************使用静态页面生成技术***********************************
    @Autowired
    private TemplateEngine templateEngine;//Thymeleaf的引擎模板，对模板进行渲染
    //Thymeleaf在后台是静态化技术   在前端是页面标签

    //生成静态化页面到指定位置   提前准备,设置更新时间
    @GetMapping("/createHtml")
    @ResponseBody
    public Result createHtml(){
        List<Map> baseCategoryMap = productFeignClient.getBaseCategoryMap();
        Context context = new Context();
        context.setVariable("list",baseCategoryMap);
        //1.准备输出流
        Writer out = null;
        try {
            String templates = ClassUtils.getDefaultClassLoader().getResource("templates").getPath();
            out = new PrintWriter(templates+"/index.html","utf-8");
            //模板路径及模板名称   数据   输出流
            templateEngine.process("index/index",context,out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok();
    }
    //2. 直接访问此页面进入首页
    @GetMapping("/")
    public String index(){

        return "index";
    }


}
